package com.aim.Activity;


import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.ShutterCallback;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.Toast;

import com.aim.api.AIMCaseConstants;
import com.aim.util.Preferences;

public class TakePhotos extends Activity implements OnClickListener {
//	private static final String TAG = "QuickCaseActivity";
	Context mContext;
	CameraPreview cPreview;
	String caseNo;
	String operatorType;
	Button backButton;
	Button takePictureButton;
	Button nextButton;
	int flag = 0;
	int size;
	public String getOperatorType() {
		return operatorType;
	}

	public void setOperatorType(String operatorType) {
		this.operatorType = operatorType;
	}

	public String getCaseNo() {
		return caseNo;
	}

	public void setCaseNo(String caseNo) {
		this.caseNo = caseNo;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		mContext = this;
		super.onCreate(savedInstanceState);
		SharedPreferences sp = this.getSharedPreferences(Preferences.NAME, 0);
        String s = sp.getString(AIMCaseConstants.PICSIZE, "50");
        size = Integer.parseInt(s);
		load();
	}

	public void finish(){
		
		mContext = null;
		cPreview = null;
		caseNo = null;
		operatorType = null;
		backButton = null;
		takePictureButton = null;
		nextButton = null;
		
		super.finish();
	}
	@Override
	public void onStop(){
		super.onStop();
		
	}
	@Override
	public void onDestroy(){
		super.onDestroy();
		
		
	}
	@Override
	public void onResume(){
		super.onResume();
		SharedPreferences sp = this.getSharedPreferences(Preferences.NAME, 0);
        String s = sp.getString(AIMCaseConstants.PICSIZE, "50");
        size = Integer.parseInt(s);
		
		
	}
	@Override
	public void onStart(){
		super.onStart();
	}
	
	@Override
	public void onRestart(){
		super.onRestart();
	}
	private void load() {
		if(ImpoundTab.no!=null)
		{
			this.setCaseNo(ImpoundTab.no);
		}
		else 
			{this.setCaseNo("quick");
			}
		setContentView(R.layout.takephotos);
		cPreview = new CameraPreview(this);
		this.backButton = (Button) findViewById(R.id.backButton);
		this.takePictureButton = (Button) findViewById(R.id.takePictureButton);
		this.nextButton = (Button) findViewById(R.id.nextButton);
		
		backButton.setOnClickListener(this);
		takePictureButton.setOnClickListener(this);
		nextButton.setOnClickListener(this);
		nextButton.setClickable(false);
		((FrameLayout) findViewById(R.id.preview)).addView(cPreview);
	}

	ShutterCallback shutterCallback = new ShutterCallback() {
		public void onShutter() {

		}
	};

	PictureCallback rawCallback = new PictureCallback() {
		public void onPictureTaken(byte[] data, Camera camera) {

		}
	};

	PictureCallback jpegCallback = new PictureCallback() {
		public void onPictureTaken(byte[] data, Camera camera) {
			
			boolean a = savePictureToLocalFile(data);
			if (a) 
			nextButton.setClickable(true);
			
		}
	};

	private boolean savePictureToLocalFile(byte[] data) {
		String pictureFileName;
		if (ImpoundTab.impoundState==2)
			pictureFileName = String.format(AIMCaseConstants.SAVEDDIRECTORY
			+ImpoundTab.no+"img"+ ShowPhotos.picNo+".jpg",
			System.currentTimeMillis());
		else
			pictureFileName = String.format(AIMCaseConstants.SAVEDDIRECTORY
				+ AIMCaseConstants.QUICKIMAGENAME + ShowPhotos.picNo+".jpg",
				System.currentTimeMillis());
		
		FileOutputStream outStream = null;
		try {
			BitmapFactory.Options options = new BitmapFactory.Options();

			Bitmap myImage = BitmapFactory.decodeByteArray(data, 0,
					data.length,options);
			//The new size we want to scale to
			
	        int REQUIRED_SIZE=320;
	        if(size!=80)
	        	
	        	REQUIRED_SIZE=160;
	        	
	        	

	        //Find the correct scale value. It should be the power of 2.
	        int width_tmp=options.outWidth, height_tmp=options.outHeight;
	        int scale=1;
	        while(true){
	            if(width_tmp/2<REQUIRED_SIZE && height_tmp/2<REQUIRED_SIZE)
	                break;
	            width_tmp/=2;
	            height_tmp/=2;
	            scale*=2;
	            Log.e(size+"",scale+"!!");
	        }

	        //Decode with inSampleSize
	        BitmapFactory.Options o2 = new BitmapFactory.Options();
	        o2.inSampleSize=scale;
			myImage = BitmapFactory.decodeByteArray(data, 0, data.length,
					o2);

//			if(data.length>50000)
//			{
////				int a = data.length;
//				double a = 50000.0/data.length;
//				
//				Double b = Math.sqrt(a*tempSize*tempSize);
//				tempSize = b.intValue();
//				Log.e("length!!!"+tempSize, data.length+"  !!!!!");
//			}
//			Log.e("length!!!"+tempSize, data.length+"  !!!!!");
			
			
			outStream = new FileOutputStream(pictureFileName);
		
			BufferedOutputStream bos = new BufferedOutputStream(outStream);

			myImage.compress(CompressFormat.JPEG, 100, bos);

			myImage.recycle();
			bos.flush();
			bos.close();
			File mF = new File(pictureFileName);
			Log.e("!", pictureFileName);
			Log.e("picsize!!!", mF.length()+"  !!!!!");
			return true;
		} catch (FileNotFoundException e) {
			Log.e("TakePictureActivity", "FileNot Found Exception", e);
			pictureFileName = "";
		} catch (IOException e) {
			Log.e("TakePictureActivity", "IOException", e);
			pictureFileName = "";
		} finally {

		}
		return false;
	}

	/**
	 * implement the action listener
	 */
	public void onClick(View v) {
		if (v.equals(takePictureButton)) {
			if (flag == 0) {
				ShowPhotos.picNo++;
				Log.e("press", ShowPhotos.picNo+"");
				this.setOperatorType(AIMCaseConstants.SAVETOLOCAL);
				cPreview.camera.takePicture(shutterCallback, rawCallback,
						jpegCallback);
				
				takePictureButton.setText("Delete");
				takePictureButton.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.delete_unselected, 0, 0);
				
				cPreview.camera.stopPreview();
				
				flag = 1;
			} else {
				File deletepic;
				if (ImpoundTab.impoundState==2)
					 deletepic = new File(AIMCaseConstants.SAVEDDIRECTORY
					+ImpoundTab.no+"img"+ ShowPhotos.picNo+".jpg");
				else
					deletepic = new File(AIMCaseConstants.SAVEDDIRECTORY
							+ AIMCaseConstants.QUICKIMAGENAME + ShowPhotos.picNo+".jpg");
				deletepic.delete();
				ShowPhotos.picNo--;
				Log.e("after delete",ShowPhotos.picNo+"");
//				backButton.setEnabled(false);
				try {
					cPreview.camera.startPreview();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				flag = 0;
				
//				takePictureButton.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
				takePictureButton.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.camera_unselected, 0, 0);
				
				takePictureButton.setText("Take");
				nextButton.setClickable(false);
			}
		} 
		else if (v.equals(backButton)) {

			this.finish();

//			
		} 
		
		else if (v.equals(nextButton)) {
			
			
				if (ShowPhotos.picNo<ImpoundTab.LIMIT){
				try {
					
					cPreview.camera.startPreview();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			Toast.makeText(mContext, "picNo: "+ShowPhotos.picNo+" saved",
	                Toast.LENGTH_SHORT).show();
			flag = 0;
			takePictureButton.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.camera_unselected, 0, 0);
			
			takePictureButton.setText("Take");
			}
			else {
				Toast.makeText(mContext, "picNo: "+ShowPhotos.picNo+" saved, U can save "+ImpoundTab.LIMIT+" pictures for one case at most",
	                Toast.LENGTH_LONG).show();
			
			}
			nextButton.setClickable(false);

		}

	}
}
